import { useCallback, useEffect, useMemo } from 'react'
import { getCurrentInstance, useRouter } from '@tarojs/taro'
import { ACQUIRE_CHANNEL } from '@CONSTANTS/app'
import { useDispatch, useSelector } from 'react-redux'
import authActions from '@ACTIONS/auth'
import profileActions from '@ACTIONS/profile'
import { ACQUIRE_CHANNEL_ENUM } from '@CONSTANTS/profile'
import { ExternalIdITF } from '@INTERFACES/user'
import { setAcquireChannel } from '@UTILS/user'

const useSpringRainLogin = ():void => {
  const router = useRouter()
  const params = useMemo(() => router?.params, [router])
  const { aC = '', userId = '', appKey = '' } = params
  const user = useSelector(state => state.profile.user)
  const externalId = useMemo(() => user?.ExternalIds?.find((external : ExternalIdITF) => external.Value === userId), [user, userId])
  const dispatch = useDispatch()
  const { dispatchVisitorLogin } = authActions
  const { dispatchSetAcquireChannel } = profileActions
  const visitorLogin = useCallback(params => dispatch(dispatchVisitorLogin(params)), [dispatch, dispatchVisitorLogin])
  const setAcquireChannelAction = useCallback(type => dispatch(dispatchSetAcquireChannel(type)), [dispatch, dispatchSetAcquireChannel])

  useEffect(() => {
    if (aC === ACQUIRE_CHANNEL.SpringRain) {
      setAcquireChannelAction(ACQUIRE_CHANNEL.SpringRain)
      setAcquireChannel(ACQUIRE_CHANNEL.SpringRain)
      Taro.hideTabBar()
      // @ts-ignore
      const items = getCurrentInstance()?.app?.config.tabBar.list
      if (Array.isArray(items) && items.length > 0) {
        items.splice(2, 2)
        Taro.showTabBar()
      }

      if (!externalId) {
        visitorLogin({ ClientKey: appKey, ExternalId: userId })
      }
    }
  }, [externalId, aC, userId, appKey, visitorLogin, setAcquireChannelAction])
}

export const useAcPermission = () => {
  const acquireChannel = useSelector(state => state.profile.acquireChannel)
  return ({
    isSpringRain: acquireChannel === ACQUIRE_CHANNEL_ENUM.SpringRain
  })
}

export default useSpringRainLogin
